package ee.maoinvest.backend.model.dao.postgresqlimplementations;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import org.apache.log4j.Logger;
import ee.maoinvest.backend.database.ConnectionManager;
import ee.maoinvest.backend.model.dao.ElectricityMeterReadingFullCircleDAO;
import ee.maoinvest.backend.model.data.ElectricityMeterReadingFullCircle;

public class ElectricityMeterReadingFullCircleDAOPostgresqlImpl implements ElectricityMeterReadingFullCircleDAO
{
	Logger logger = Logger.getLogger(ElectricityMeterReadingFullCircleDAOPostgresqlImpl.class);
	Connection dbConnection;
	String sql;
	PreparedStatement preparedStatement;
	Statement statement;
	ResultSet resultSet;
	private final int WARNING_NO_ROWS_AFFECTED = 0;
	private int rowsAffected;
	
	public ElectricityMeterReadingFullCircleDAOPostgresqlImpl(Connection dbConnection)
	{
		this.dbConnection = dbConnection;
	}
	
	
	@Override
	public int insertElectricityMeterReadingFullCircle(
			ElectricityMeterReadingFullCircle electricityMeterReadingFullCircle) 
	{
		resultSet = null;
		rowsAffected = WARNING_NO_ROWS_AFFECTED;
		sql = "INSERT INTO Electricity_meter_reading_full_circles " +
				"(electricityMeterFK, readingTypeThatMadeFullCircleFK, dateReadingMadeFullCircle) " +
				"VALUES (?, ?, ?)";
		
		try 
		{
			preparedStatement = dbConnection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
			
			preparedStatement.setInt	(1, electricityMeterReadingFullCircle.getElectricityMeterFK());
			preparedStatement.setInt	(2, electricityMeterReadingFullCircle.getReadingTypeThatMadeFullCircleFK());
			preparedStatement.setDate	(3, electricityMeterReadingFullCircle.getDateReadingMadeFullCircle());
			
			rowsAffected = preparedStatement.executeUpdate();
			
			if (rowsAffected == 1)
			{
				resultSet = preparedStatement.getGeneratedKeys();
				resultSet.next(); //answer consist only 1 row, so move the cursor just once to start to process the result
				int newId = resultSet.getInt(1); // 1, because identifiers are held in the first column 
				electricityMeterReadingFullCircle.setElectricityMeterReadingFullCircleID(newId);
				logger.info("Successful insertion to a database: " + preparedStatement.toString());
				return rowsAffected;
			}
			else
			{
				System.out.println("No rows affected!");
				logger.info("Unsuccessful insertion to a database: " + preparedStatement.toString());
				return WARNING_NO_ROWS_AFFECTED;
			}
		}
		catch (Exception e) 
		{
			e.printStackTrace();
			return WARNING_NO_ROWS_AFFECTED;
		}
		finally
		{
			ConnectionManager.getInstance().closeStatement(preparedStatement);
			ConnectionManager.getInstance().closeResultSet(resultSet);
		}
	}
}
